<?php
/**
* @author moufer<moufer@163.com>
* @copyright (c)2001-2009 Moufersoft
* @website www.modoer.com
*/
!defined('IN_MUDDER') && exit('Access Denied');

/**
* google账号登录二次封装
*/
class oauth2_google extends ms_oauth2
{
	public $name = 'google';
	
	private $client = null;
	private $openid = '';

	private $callback_url = 'api/auth_callback/google';

	function __construct()
	{
		parent::__construct();
		if(!class_exists('Google_Client')) {
			require(MUDDER_ROOT.'api'.DS.'third_party'.DS.'autoload.php');
		}
		$this->client = new Google_Client();
		$this->client->setClientId(S('member:passport_google_appid'));
 		$this->client->setClientSecret(S('member:passport_google_appsecret'));
 		$this->callback_url = S('siteurl').$this->callback_url;
		$this->client->setRedirectUri($this->callback_url);
		//权限
 		$scope = array (
 			Google_Service_Oauth2::PLUS_LOGIN,
 			Google_Service_Oauth2::PLUS_ME,
 			Google_Service_Oauth2::USERINFO_EMAIL
 		);
 		$this->client->addScope($scope);
	}

	function getAuthorizeURL($callback_url)
	{
		return $this->client->createAuthUrl();
	}

	function getAccessToken($callback_url = '')
	{
		if (isset($_GET['code'])) {
			try {
				$this->client->authenticate($_GET['code']);
			} catch (Google_Auth_Exception $e) {
				log_write('oauth2_google', request_uri()."\n".$e->getMessage()."\n");
				if(DEBUG) {
					vp($e->getMessage());
				}
				return;
			}
		}
  		$token_data = $this->client->getAccessToken();
  		if(!$token_data) return;

  		$token = json_decode($token_data, true);
  		if(!$token['access_token']) return;

        $access_token = $token['access_token'];
        $expires_in = _G('timestamp') + $token['expires_in'];

        $oauth = new Google_Service_Oauth2($this->client);
        $user_data = $oauth->userinfo->get();

		$newtoken = array (
			'name' 			=> $this->name, 
			'id'			=> $user_data['id'],
			'username'		=> $user_data['name'],
			'access_token' 	=> $access_token, 
			'expires_in' 	=> $expires_in,		//授权剩余时间
			'token_data'	=> $token_data,		//json 形式 token data
		);
		return $this->_createToken($newtoken);
	}

	function getUserInfo($token = '')
	{
		$userinfo = array();
		try {
			$this->client->setAccessToken($token->token_data);
			$oauth = new Google_Service_Oauth2($this->client);
        	$user_data = $oauth->userinfo->get();
		} catch (Exception $e) {
			return $userinfo = array();
		}
	    
	    $userinfo['username'] = $user_data['name'];
	    $userinfo['passport_id'] = $user_data['id'];
	    $userinfo['email'] = $user_data['email'];

	    if(strtoupper(_G('charset')) != 'UTF-8') {
	        foreach($userinfo as $k => $v) {
	            if(is_string($v)) $userinfo[$k] = charset_convert($v,'utf-8',_G('charset'));
	        }
	    }

	    return $userinfo;
	}
}